(function() {
    'use strict';

    /**
     * @ngdoc service
     * @name webApp.myrest
     * @dhfprinterService
     * # myrest
     * Service in the webApp.

    controller中使用样例和参数说明：
    
        function testdata() {

            var height = 480;
            var width = 869;
            var pheight = Math.round(height / 300);
            var pwidth = Math.round(width / 300);
            var request_id = helper.guid();

            return {
                // review: true, //是否预览，true时，同步返回pdf文件的base64结果
                sync: false, //是否同步打印，true：等待打印机打印完毕返回；false：任务提交给打印机返回，不能确定是否真实打印成功。默认false
                request_id: request_id, //每次请求的唯一id，如果是相同的打印内容，可以使用同一个request_id防止重复
                html: '<html><title>' + request_id + '</title><style>@page {margin: 0px;}</style><body style="margin:0px;border: solid 1px #000;"><div style="background-color: #ccc;width:' + width + 'px;height:' + height + 'px;">测试打印页面内容' + random(99999999) + '</div></body></html>',
                height: height, //打印的页面高度，单位px
                width: width, //打印的页面宽度，单位px
                // printer: "EPSON LQ-730K ESC/P 2", //打印机名称，通过dhfprinterService.getPrinters获取
                printer: "HP_LaserJet_Professional_P1108", //打印机名称，通过dhfprinterService.getPrinters获取
                parms: {
                    name: "大黄蜂", //其他参数，暂不用
                    title: "中国", //其他参数，暂不用
                },
            };
        }

        //测试打印
        $scope.print = function() {
            var testData = testdata();
            testData.review = false; //不预览，直接打印
            dhfprinterService.print(testData).then(function(a) {
                console.log("返回结果：", a);
            });
        }

        //测试预览
        $scope.printreview = function() {
            var testData = testdata();
            testData.review = true; //预览，不打印
            dhfprinterService.print(testData).then(function(a) {
                console.log("返回结果：", a);
            });
        }

        //打印机
        $scope.printers = function() {
            dhfprinterService.getPrinters().then(function(a) {
                console.log("返回结果：", a);
            });
        }



     */
    angular.module('webApp')
        .service('dhfprinterService', ['$rootScope', '$http', '$q', '$log', 'cacheService', 'sessionService', 'authService', 'ERP_CONFIG', 'md5', 'moment', '$filter', 'helper', 'dataService', '$timeout',
            function($rootScope, $http, $q, $log, cacheService, sessionService, authService, ERP_CONFIG, md5, moment, $filter, helper, dataService, $timeout) {
                // var paramArr = [];
                var socket;
                var prsocket;
                var reconneting = 0;
                if (cacheService.get($rootScope.store_id + "print")) {
                    init();
                }
                $rootScope.$on('event:kq-print', function() {
                    init();
                });
                $rootScope.$on('event:gb-print', function() {
                    close();
                });

                // Setup reactor
                var callbacks = {};
                var messages = {
                    requests: [],
                    unhandled: []
                };

                function send(request) {
                    var deferred = $q.defer();
                    callbacks[request.request_id] = deferred;
                    messages.requests.push(request);
                    // console.log("-------", request, socket);
                    if (socket && socket.readyState == 1) {
                        // console.log("-------发出请求：", request, socket);
                        socket.send(angular.toJson(request));
                    } else {
                        init();
                        $rootScope.$on('event:printer-opened', function() {
                            socket.send(angular.toJson(request));
                        });
                    }
                    // console.error("response", deferred);
                    return deferred.promise.then(function(response) {
                        // console.error("response;;;;;;;", response);
                        request.response = response;
                        return response;
                    });
                }

                //连接打印客户端
                function init() {
                    try {
                        console.info("init打印组件，门店：", $rootScope.store_id);
                        socket = new WebSocket('wss://local.print.dhf.app:41021');
                        var loReconnect = 0;
                        socket.onmessage = function(event) {
                            var data = angular.fromJson(event.data);
                            console.info("打印组件消息:", data);
                            if (angular.isDefined(callbacks[data.request_id])) {
                                var callback = callbacks[data.request_id];
                                delete callbacks[data.request_id];
                                callback.resolve(data);
                            } else {
                                messages.unhandled.push(data);
                            }
                        };

                        // 监听Socket的open
                        socket.onopen = function(event) {
                            console.info('链接上打印组件：', event);
                            helper.message("打印组件连接成功！", 'success');
                            $rootScope.$broadcast("event:printer-opened");
                            loReconnect = 1;
                            wsautoPrint();
                        };

                        // 监听Socket的关闭
                        socket.onclose = function(event) {
                            console.info('打印组件关闭：', event);
                            $rootScope.$broadcast("event:printer-closed");
                            loReconnect = 0;
                            if (cacheService.get($rootScope.store_id + "print_type")) {
                                if (!loReconnect) {
                                    $timeout(function() {
                                        console.log("重新链接...");
                                        init();
                                    }, 100000)
                                }
                            } else {
                                // helper.message("打印组件已关闭！", 'error');
                            }

                        };

                        socket.onerror = function(event) {
                            console.info('打印组件错误：', event);
                            var html = '<div style="text-align: center;margin-top:20px"> <div>客户端连接失败!</div><div>请重启打印客户端!</div><div>没有安装请安装打印客户端：<span><a href="https://img.dhfapp.com/static/uploads/dhf-printer-win32-x64.zip">下载</a></span></div> </div>';
                            helper.rmAlert();
                            helper.myAlert(html, null, 60, function() {
                                helper.myConfirm("是否选择关闭链接打印组件？", function() {
                                    cacheService.set($rootScope.store_id + "print_type", 0);
                                });
                            });
                            // $rootScope.$broadcast("event:printer-closed");
                        };
                    } catch (e) {}
                }

                function close() {
                    socket.close();
                    helper.message("打印组件关闭连接！", 'error');
                    // console.log('客户端关闭：',socket);
                    // $rootScope.$broadcast("event:printer-closed");
                }

                //连接线上的ws连接
                function wsautoPrint() {
                    console.error("init自动打印组件，门店：", $rootScope.store_id);
                    var token = sessionService.get('token');
                    var Reconnect;
                    prsocket = new WebSocket(ERP_CONFIG.wsUrl + '/wsauto/print/join?store_id=' + $rootScope.store_id + "&token=" + token);
                    prsocket.onmessage = function(event) {
                        var data = JSON.parse(event.data);
                        console.error("服务端打印消息:", data);
                        if (data.content) {
                            _.map(data.content, function(da, kke) {
                                if (da.order_id) {
                                    prsocketOnmessage(da.order_id);
                                }
                            });
                        }
                    };
                    // 监听Socket的open
                    prsocket.onopen = function(event) {
                        Reconnect = 1;
                        console.error('服务端链接上成功：', event);
                        helper.message("自动打印组件连接成功！", 'success');
                    };
                    // 监听Socket的关闭
                    prsocket.onclose = function(event) {
                        console.error('服务端关闭：', event);
                        helper.message("服务端组件关闭连接！", 'error');
                        Reconnect = 0;
                        if (cacheService.get($rootScope.store_id + "print_type")) {
                            if (!Reconnect) {
                                $timeout(function() {
                                    console.log("重新链接...");
                                    helper.message("打印组件连接中...", "error");
                                    wsautoPrint();
                                }, 10000)
                            }
                        }
                    };

                    prsocket.onerror = function(event) {
                        console.error('服务端错误：', event);
                    };
                }
                //
                function prsocketOnmessage(order_id) {
                    //查询默认的模板的打印机  
                    //查询默认物流公司
                    var query = {
                        tep_type: 2,
                        default_express: 1,
                        default_template: 1,
                        store_id: $rootScope.store_id
                    };
                    dataService.printSellerGet({
                        query: query
                    }).then(function(result) {
                        if (result.prints && result.prints.length > 0) {
                            var selectUserTpl = result.prints[0];
                            if (!selectUserTpl.default_printer) {
                                helper.message("请先设置默认打印机！", "error", "#/print/list");
                            } else {
                                //console.log(" $scope.selectUserTpl ", selectUserTpl);
                                var printers = JSON.parse(selectUserTpl.default_printer);
                                getdata(printers, order_id, selectUserTpl.print_id);
                            }

                        } else {
                            helper.message("请先设置默认打印模板！", "error", "#/print/list");
                        }
                    });
                }
                //获取模板数据
                function getdata(printers, tid, templateid) {
                    var data = {
                        content: {
                            "store_id": $rootScope.store_id,
                            "tid": tid,
                            "templateid": templateid,
                            "timezone": window.localStorage.timezone,
                        }
                    }
                    var printData;
                    console.error("rootScope", $rootScope, window.localStorage.timezone);
                    return dataService.printPOs(data).then(function(result) {
                        if (result) {
                            if (result.Msg) {
                                helper.myAlert(tid + result.Msg);
                                return;
                            } else {
                                if (result.type == 2) {
                                    printData = result;
                                    return implementPrint(printers, printData, null);
                                } else {
                                    printData = result.printdata;
                                    return generateHtml(printData).then(function(datahtml) {
                                        return implementPrint(printers, printData, datahtml);
                                    });
                                }
                            }
                            console.error("$scope.printData", printData);
                        }
                    });
                }

                //解析模板参数
                function generateHtml(printData) {
                    var g_express_info = JSON.parse(printData.content);
                    var g_express = JSON.parse(g_express_info.value);
                    var taghtmlstr;
                    for (var i = 0; i < g_express.length; i++) {
                        var name = ' ';
                        var possize = g_express[i]['left'] + ',' + g_express[i]['top'] + ',' + g_express[i]['width'] + ',' + g_express[i]['height'];
                        if ($scope.printData[g_express[i]['id']]) {
                            name = $scope.printData[g_express[i]['id']];
                        }
                        if (g_express[i]['id'] == 'zdy') {
                            name = g_express[i]['name'];
                        }
                        taghtmlstr += MakeOnetagHtml(name, possize, 3, g_express[i]['font-family'], g_express[i]['font-size'], g_express[i]['font-weight'], g_express[i]['white-space'], g_express[i]['img'], g_express[i]['flg'], g_express[i]['id']);
                    }

                    return dataService.resolve(taghtmlstr);
                }

                function implementPrint(printers, printData, taghtmlstr) {

                    var html;
                    var escpos = 0;
                    if (!taghtmlstr) {
                        escpos = 1;
                        html = printData.printdata; // ="G0AdIQAcJhwuHSERHCYcLh0hABwmHC4dIQAcJhwuHSEAHCYcLh0hABwmHC4dIQAcJhwuHSERHCYcLh0hABwmHC4dIQAcJhwuHSEAHCYcLh0hABwmHC4dIQAcJhwuHSEAHCYcLh0hABwmHC4dIQAcJhwuHSEAHCYcLh0hABwmHC4dIQAcJhwuHSEAHCYcLh0hABwmHC4dIQAcJhwuHSEAHCYcLh0hABwmHC4dIQAcJhwuHSEi";
                    } else {
                        html = '<html><title>' + request_id + '</title><body><div >' + taghtmlstr + '</div></body></html>';
                    }

                    async.map(printers, function(data, callback) {
                        console.error(data);
                        var request_id = helper.guid();
                        var testData = {
                            sync: false, //是否同步打印，true：等待打印机打印完毕返回；false：任务提交给打印机返回，不能确定是否真实打印成功。默认false
                            request_id: request_id, //每次请求的唯一id，如果是相同的打印内容，可以使用同一个request_id防止重复
                            html: html,
                            height: printData.height, //打印的页面高度，单位px
                            width: printData.width, //打印的页面宽度，单位px
                            printer: data, //打印机名称，通过dhfprinterService.getPrinters获取
                            parms: {
                                escpos: escpos,
                            },
                        };
                        console.log("testData", testData);
                        testData.review = false; //不预览，直接打印
                        print(testData).then(function(a) {
                            console.log("返回结果：", a);
                            helper.message("打印机" + data + "执行" + (a.msg ? a.msg : "打印成功"), "success");
                            callback(a, null);
                        });

                    }, function(e, r) {
                        return dataService.resolve(e);
                    });
                }
                /****************
                 * 打印
                 */

                function print(request) {
                    request.cmd = "print";
                    console.error("print执行");
                    return send(request);
                }

                /****************
                 * 请求打印机列表
                 */

                function getPrinters() {
                    var request = {
                        cmd: "getPrinters",
                        request_id: helper.guid(),
                    };

                    return send(request);
                }

                /****************
                 * 打印机参数
                 */

                function getPrinterDriverOptions(name) {
                    var request = {
                        cmd: "getPrinterDriverOptions",
                        request_id: helper.guid(),
                        name: name,
                    };

                    return send(request);
                }

                //对外提供如 下接口
                return {
                    print: print,
                    getPrinters: getPrinters,
                    getPrinterDriverOptions: getPrinterDriverOptions,
                    prsocketOnmessage: prsocketOnmessage,
                };
            }
        ]);
})();